# coding:utf-8
import pymysql

import pandas as pd
import csv
import re
import numpy as np
from datetime import datetime

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="hui123456", db='dbtest')
# 使用cursor()方法创建一个游标对象cursor
cursor = db.cursor()


sql = """ \
      SELECT month (day) as "日期", Product_BianMa as "商家编码", SUM (Product_num) as "商品数量" \
      from doudian_day \
      WHERE MONTH (day)=10 \
        AND ( order_zt="已签收" \
         OR order_zt="待发货" \
         OR order_zt="已完成" \
         OR order_zt="已发货" \
         OR order_zt="已支付") \
        AND order_sh != "退款成功" \
        AND order_sh != "售后完成" \
        AND order_sh != "退款完成" \
        AND order_sh != "已全额退款" \
      group by month (day), Product_BianMa
    """

sql1 = """ \
       select month (day) as "日期", Product_BianMa as "商家编码", SUM (Product_num) as "商品数量" \
       from niandu_day \
       WHERE MONTH (day)=10 \
         and (order_zt="完成" \
          OR order_zt="等待出库" \
          OR order_zt="等待确认收货" \
          OR order_zt="已签收" \
          OR order_zt="待配货" \
          OR order_zt="待发货" \
          OR order_zt="交易成功" \
          OR order_zt="已完成" \
          OR order_zt="卖家已发货，等待买家确认" \
          OR order_zt="买家已付款，等待卖家发货" \
          OR order_zt="已发货" \
          OR order_zt="调度中" \
          OR order_zt="已收货" \
          OR order_zt="已发货未签收" \
          OR order_zt="已发货，待签收" \
          OR order_zt="(锁定)等待确认收货" \
          OR order_zt="已发货，待收货" \
          OR order_zt="(锁定)等待确认收货" \
          OR order_zt="部分发货" \
          OR order_zt="买家已付款,等待卖家发货" \
          OR order_zt="卖家已发货" \
          OR order_zt="买家已付款" \
          OR order_zt="发货即将超时" \
          OR order_zt="卖家部分发货" \
          OR order_zt="待买家收货" \
          OR order_zt="待卖家发货" \
          OR order_zt="部分发货中") \
         AND order_sh != "退款成功" \
         AND order_sh != "售后完成" \
         AND order_sh != "退款完成" \
         AND order_sh != "退货退款完成 " \
       group by month (day), Product_BianMa
     """

cursor.execute(sql)
result = cursor.fetchall()
cursor.execute(sql1)
result1 = cursor.fetchall()
xs1 = pd.DataFrame(list(result), columns=['日期', '商家编码', '商品数量'])
xs11 = pd.DataFrame(list(result1), columns=['日期', '商家编码', '商品数量'])
date_concat_dl = pd.concat([xs1, xs11])

date_concat_dl['商品数量'] = date_concat_dl['商品数量'].map(lambda x: int(x))

# date_concat_dl=xs.groupby([xs['日期'],xs['商家编码']],as_index=False).agg(商品数量=('商品数量','sum'))
douchao = pd.read_excel(r'G:\工作\2025年订单\10月\抖超.xlsx')

maochao = pd.read_excel(r'G:\工作\2025年订单\10月\猫超.xlsx')
ziying1 = pd.read_excel(r'G:\工作\2025年订单\10月\自营1.xlsx')
ziying2 = pd.read_excel(r'G:\工作\2025年订单\10月\自营2.xlsx')

ziying2_dl = pd.read_excel(r'G:\工作\2025年订单\10月\自营2.xlsx')

pp1 = pd.read_excel(r'G:\工作\猫超+自营SKU编码.xlsx', dtype={'SKU': str})
# print(pp)
douchao['退款成功金额'] = 0
douchao['平台'] = '抖音超市'
douchao['月'] = douchao['日期'].map(lambda x: str(x)[0:6])  # 调整
douchao_date = douchao.loc[
    :, ['月', '货品ID', '支付货品件数', '支付GMV', '退款成功金额', '支付货品件数', '平台', '货品名']]  # 无退款
douchao_date.columns = ['日期', 'SKU', '销售单量', '销售额', '退款金额', '成交商品件数', '平台', '产品名称']

maochao['商品数量'] = maochao['支付商品件数'] - maochao['退款成功商品件数']
maochao['平台'] = '猫超'
maochao['月'] = maochao['统计日期'].map(lambda x: f"{str(x)[0:4]}-{str(x)[4:6]}-{str(x)[6:8]}" if len(str(x)) >= 8 else str(x)[0:8])
maochao_date = maochao.loc[
    :, ['月', '商品ID', '支付子订单数(剔退款)', '支付金额(剔退款)', '退款成功金额', '商品数量', '平台']]
maochao_date.columns = ['日期', 'SKU', '销售单量', '销售额', '退款金额', '成交商品件数', '平台']

ziying1['退款成功金额'] = 0
ziying1['平台'] = '京东自营1'
ziying1_date = ziying1.loc[:, ['时间', 'SKU', '成交单量', '成交金额', '退款成功金额', '成交商品件数', '平台']]

ziying1_date.columns = ['日期', 'SKU', '销售单量', '销售额', '退款金额', '成交商品件数', '平台']

ziying2 = ziying2[
    (ziying2['SKU'] != 100095090135) & (ziying2['SKU'] != 100111765304) & (ziying2['SKU'] != 100111765306) & (
                ziying2['SKU'] != 100122053209)]
ziying2['退款成功金额'] = 0
ziying2['平台'] = '京东自营2'
ziying2_date = ziying2.loc[:, ['时间', 'SKU', '成交单量', '成交金额', '退款成功金额', '成交商品件数', '平台']]

ziying2_date.columns = ['日期', 'SKU', '销售单量', '销售额', '退款金额', '成交商品件数', '平台']

ziying2_dl['退款成功金额'] = 0
ziying2_dl['平台'] = '京东自营2'
ziying2dl_date = ziying2_dl.loc[:, ['时间', 'SKU', '成交单量', '成交金额', '退款成功金额', '成交商品件数', '平台']]
ziying2dl_date.columns = ['日期', 'SKU', '销售单量', '销售额', '退款金额', '成交商品件数', '平台']

res_dl = pd.concat([maochao_date, ziying1_date, ziying2dl_date])
# ['商家编码']去空格
res_dl['SKU'] = res_dl['SKU'].astype(str).str.strip()
res_mdl = pd.merge(res_dl, pp1, on=['SKU'], how='left')

result_dl = pd.concat([res_mdl, douchao_date])

mc = result_dl
pp = pd.read_excel(r'G:\工作\商家编码匹配产品-11月.xlsx')  # 匹配表
pp_zh = pd.read_excel(r'G:\工作\商家编码匹配产品-11月.xlsx', sheet_name='组合装')  # 匹配表
mc = mc[mc['成交商品件数'] > 0]
mc_date = mc.loc[:, ['日期', '产品名称', '成交商品件数']]
mc_date.columns = ['日期', '商家编码', '商品数量']

result = pd.concat([date_concat_dl, mc_date])

# ['商家编码']去空格
result['商家编码'] = result['商家编码'].str.strip()
# 去空值
result.dropna(subset=['商家编码'], inplace=True)
# 去掉抖音直播间赠品，电煮锅，空值
result = result[(result['商家编码'] != 'logo定制电煮锅1个') & (result['商家编码'] != '抖音直播间赠品')]

# 所有产品，包含组合装
# 处理每行多订单情况
# 分列
s_1 = []  # 分列后以列表形式保存
r_1 = []  # 添加每个分列后的产品
r_3 = []  # 添加商品数量
r_4 = []  # 添加平台
r_5 = []  # 添加平台1 线上
r_6 = []  # 添加月
for date_s in list(result['商家编码']):
    if '+' in date_s:
        date_split = str(date_s).split('+')
        s_1.append(date_split)

    elif '，' in date_s:
        date_split = str(date_s).split('，')
        if '赠' in date_split[0]:
            date_split_1 = date_split[0].split('赠')
            s_1.append(date_split_1)
        else:
            s_1.append([date_split[0]])


    elif '赠' in date_s:

        date_split = str(date_s).split('赠')
        s_1.append(date_split)


    elif '＋' in date_s:
        date_split = str(date_s).split('＋')
        s_1.append(date_split)
    else:
        s_1.append([date_s])

result['编码分裂'] = s_1

# date_concat.reindex(range(len(date_concat['编码分裂'])))
date_concat_s = result.reset_index(drop=True)

# print(date_concat_s)
# cc=date_concat_s['编码分裂']

n = 0
for i in list(date_concat_s['编码分裂']):

    # 查i对应的索引值
    # n=list(date_concat['编码分裂']).index(i)
    # 分裂后生成的是列表，所以用列表长度判定
    if len(i) == 1:  # 判定是否有多的订单
        r_1.append(i[0])
        r_3.append(list(date_concat_s['商品数量'])[n])
        r_4.append(list(date_concat_s['日期'])[n])
        # r_5.append(list(date_concat_s['平台1'])[n])
        r_6.append(list(date_concat_s['商家编码'])[n])

    else:  # 多订单的情况下分行并对应单量
        for c in i:
            r_1.append(c)
            r_3.append(list(date_concat_s['商品数量'])[n])
            r_4.append(list(date_concat_s['日期'])[n])
            # r_5.append(list(date_concat_s['平台1'])[n])
            r_6.append(list(date_concat_s['商家编码'])[n])

    n += 1
# s={'SKU':r_6,'商家编码':r_1,'商品数量':r_3,'平台':r_4,'平台1':r_5}
s = {'日期': r_4, 'SKU': r_6, '商家编码': r_1, '商品数量': r_3}
res_d = pd.DataFrame(s)
# print(result)
# res.to_excel(r'G:\结果\分列4.xlsx')

# 处理土豆粉出单

result_hz = res_d.groupby([res_d['日期'], res_d['SKU'], res_d['商家编码']], as_index=False).sum()

# result_hz.reset_index(drop=False)


result_re = pd.merge(result_hz, pp, on=['商家编码'], how='left')


# 提取商品袋数
def d(x):
    if '袋' in x:
        return re.findall(r"(\d+)袋", x)[-1]
    elif '桶' in x:
        return re.findall(r"(\d+)桶", x)[-1]
    elif ('个' in x):
        try:
            return re.findall(r"(\d+)个", x)[-1]
        except:
            return 1

    elif '包' in x:
        return re.findall(r"(\d+)包", x)[-1]
    elif ('只' in x):
        return re.findall(r"(\d+)只", x)[-1]
    elif ('根' in x):
        return re.findall(r"(\d+)根", x)[-1]
    else:
        return 0


result_re['件数'] = result_re['商家编码'].map(d)

result_re['件数'] = result_re['件数'].astype(int)

# result_res.to_excel(r'G:\结果\产品订单量结果_新5月.xlsx')
result_re['总件数'] = result_re['商品数量'] * result_re['件数']

result_re.to_excel(r'G:\工作\2025年订单\10月\结果\SKU结果_10月.xlsx')
